package com.ztjy.utils;

import com.ztjy.annonation.MyLog;
import com.ztjy.bean.Journal;
import com.ztjy.bean.Users;
import com.ztjy.sys.biz.SysLogBiz;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 系统日志：切面处理类
 * 参考网址：https://blog.csdn.net/qq_40112545/article/details/88820079
 */
@Aspect
@Component
public class SysLogAspect {
    @Autowired
    private SysLogBiz sysLogBiz;

    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation( com.ztjy.annonation.MyLog)")
    public void logPoinCut() {
    }

    //切面 配置通知
    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        System.out.println("切面  后置返回通知, 在方法执行之后执行---------");
        //保存日志
        Journal sysLog = new Journal();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取操作
        StringBuffer contentSbF = new StringBuffer("操作：");
        MyLog myLog = method.getAnnotation(MyLog.class);
        if (myLog != null) {
            String value = myLog.value();
            contentSbF.append(value + "");
        }

        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        contentSbF.append("------类名.方法名：" + className + "." + methodName);

        //请求的参数
//        Object[] args = joinPoint.getArgs();
        //将参数所在的数组转换成json
//        String params = JSON.toJSONString(args);
//        contentSbF.append("------参数："+ params);

        sysLog.setJcontent(contentSbF.toString());
        //时间
        sysLog.setJdate(new Date());
        //获取用户名
        //此处用session来获取登录操作名
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();

        Users currUser = (Users) session.getAttribute("currUser");
        sysLog.setUId(currUser.getuId());

        //获取模块ID
        Integer mid = Integer.parseInt(session.getAttribute("mid").toString());
        sysLog.setModuleId(mid);

        //调用service保存SysLog实体类到数据库
        sysLogBiz.save(sysLog);
    }

}
